from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.status import HTTP_201_CREATED, HTTP_204_NO_CONTENT
from rest_framework_jwt.authentication import jwt_decode_handler

from xyz.models import User, Label
from xyz.serializers.user import UserModelSerializer, UserSerializer


class UserInfoView(APIView):
    def get_queryset(self):
        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
            my_user = User.objects.get(id=user_id)
        except:
            return Response(status=404)
        return my_user

    def get(self, request):
        try:
            queryset = self.get_queryset()
            serializer = UserModelSerializer(queryset)
            return Response(serializer.data)
        except:
            return Response({'message': '错误'}, status=404)

    def put(self, request):
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_201_CREATED)


class UserPasswordView(APIView):
    """修改密码"""

    def put(self, request):
        token = request.auth
        toke_user = jwt_decode_handler(token)
        user_id = toke_user["user_id"]
        user = User.objects.get(id=user_id)
        password = request.data.get('password')
        user.set_password(password)
        user.save()
        return Response(status=HTTP_201_CREATED)


class UserLikeView(APIView):
    def post(self, request, id):
        token = request.auth
        toke_user = jwt_decode_handler(token)
        user_id = toke_user["user_id"]
        my_user = User.objects.get(id=user_id)
        user = User.objects.get(id=id)
        my_user.fans.add(user)
        return Response({'message': '关注成功', 'success': True})

    def delete(self, request, id):
        token = request.auth
        toke_user = jwt_decode_handler(token)
        user_id = toke_user["user_id"]
        my_user = User.objects.get(id=user_id)
        user = User.objects.get(id=id)
        my_user.fans.remove(user)
        return Response({'message': '取消关注成功', 'success': True})


class UserLeabelView(APIView):
    def put(self,request):
        dict = request.data
        token = request.auth
        toke_user = jwt_decode_handler(token)
        user_id = toke_user["user_id"]
        for i,datas in dict.items():
            for data in datas:
                label = Label.objects.get(id=data)
                label.users.add(user_id)
        return Response({'message': '成功', 'success': True})

